package org.droid.campus.admin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.droid.campus.common.Enums;
import org.droid.campus.common.Enums.ActionStatus;
import org.droid.campus.common.RequestTypeException;
import org.droid.campus.common.WebActionHandler;
import org.droid.campus.util.RespStatusBuilder;

/**
 * Servlet implementation class DevClientServlet
 * 
 * @category updated at 2011-08-11 , added GZIP support
 */

public class AdminWebServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final static Logger log = Logger.getLogger(AdminWebServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdminWebServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");

		StringBuffer respData = null;
		WebActionHandler action = null;
		try {
			action = ParameterValidatorFilter.routeRequestAction(request);
			HttpServletRequest req = action.Do(request, response);
			String type = String.valueOf(req.getAttribute(Enums.ActionType.TYPE
					.getDesc()));
			String context = String.valueOf(req
					.getAttribute(Enums.ActionType.DETAIL.getDesc()));
			if (type.equals(Enums.TypeContext.FORWORD.getDesc())) {
				req.getRequestDispatcher(context).forward(req, response);
				return;
			}else
			if (type.equals(Enums.TypeContext.REDITECT.getDesc())) {
				response.sendRedirect(context);
			}else
			if(type.equals(Enums.TypeContext.CONTEXT.getDesc())) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html");
				PrintWriter pw = response.getWriter();
				pw.write(context);
				pw.flush();
				pw.close();
			}

		} catch (RequestTypeException e) {
			// TODO Auto-generated catch block
			log.error("RequestType Error : ", e);
			respData = RespStatusBuilder
					.message(ActionStatus.REQUEST_TYPE_ERROR);
		} finally {

			action = null;
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
